package com.ideal.lx_mss.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.util.PropertiesUtil;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

public class CommonUtil {
    /**
     * 创建单据编号 格式：时间戳+3位数字，不足3位补0
     * @return
     */
    public static String createFormId() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
        int i = (int)(Math.random()*900 + 100);
        String formId = sdf.format(new Date())+String.format("%0"+3+"d",i);
        return formId;
    }

    public static String createTempId() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmm");
        int i = (int)(Math.random()*900 + 100);
        String formId = sdf.format(new Date())+String.format("%0"+3+"d",i);
        return formId;
    }

    public static String  getNowTime() {
        String resultStr = "";
        String resp = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {   //防止报错，用系统时间
            resp = HttpUtil.interfaceUtil(getDateServeUrl(), "", "GET");
            JSONObject jsonObject = JSONObject.parseObject(resp);
            String data = jsonObject.getString("data");
            JSONObject jsonObject2 = JSONObject.parseObject(data);
            resultStr = jsonObject2.getString("timeStamp");
        }catch (Exception e){
            e.printStackTrace();
            resultStr = sdf.format(new Date());
        }
        System.out.println("nowTime:"+resultStr);
        return resultStr;
    }

    public static Date getNowDate() {
        Date date = new Date();
//        String resultStr = "";
//        String resp = "";
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {   //防止报错，用系统时间
//            resp = HttpUtil.interfaceUtil(getDateServeUrl(), "", "GET");
//            JSONObject jsonObject = JSONObject.parseObject(resp);
//            String data = jsonObject.getString("data");
//            JSONObject jsonObject2 = JSONObject.parseObject(data);
//            resultStr = jsonObject2.getString("timeStamp");
//        }catch (Exception e){
//            e.printStackTrace();
//            resultStr = sdf.format(new Date());
//        }
//
//        try {
//            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(resultStr);
//
//        } catch (ParseException e) {
//            //LOGGER.error("时间转换错误, string = {}", s, e);
//        }
//        System.out.println("nowDate:"+date);


        return date;
    }

    public static String getDateServeUrl(){
        PropertiesUtil p = new PropertiesUtil("application.properties");
        String timeServe = p.getStringProperty("timeServe");
        return timeServe;
    }

    /**
     * String 转date
     * @param s
     * @return
     */
    public static Date transferString2Date(String s) {
        Date date = new Date();
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(s);
        } catch (ParseException e) {
            //LOGGER.error("时间转换错误, string = {}", s, e);
        }
        return date;
    }

    public static double getDifferenceInMilliseconds(Date date1, Date date2) {
        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long abs = Math.abs(time1 - time2);
        double differenceInHours = (double) abs / (1000 * 60 * 60);
//        int differenceAsInt = (int) Math.round(differenceInHours);
        return differenceInHours;
    }


    /**
     * 是否有交叉时间
     * @param start1
     * @param end1
     * @param start2
     * @param end2
     * @return
     */
    public static boolean isOverlap(LocalTime start1, LocalTime end1, LocalTime start2, LocalTime end2) {
        return start1.isBefore(end2) && start2.isBefore(end1);
    }

    /**
     * DATE转LocalTime
     * @param date
     * @return
     */
    public static LocalTime convertToLt(Date date) {
        LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return ldt.toLocalTime();
    }


    /**
     * Date转LocalDate
     * @param date
     * @return
     */
    public static LocalDate convertToLd(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }


    public static String createRoomId() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        int i = (int)(Math.random()*900 + 100);
        String formId = sdf.format(new Date())+String.format("%0"+3+"d",i);
        return "R"+formId;
    }
    /**
     * 日期加一天
     * @param signEndDate
     * @return
     */
    public static String getCalendarAdd(String signEndDate) {
        String res = "";
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date dd = new Date();
        System.out.println("signEndDate:"+signEndDate);
        try {
            if(!signEndDate.equals("")) {
                dd = df.parse(signEndDate);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dd);
            calendar.add(Calendar.DAY_OF_MONTH, 1);//加一天
            res = df.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();

        }
        return res;
    }

    public static Map<String, String> compareWithEntity(String json, Object entity) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(json);

        Map<String, String> differences = new HashMap<>();

        // 获取实体类的所有字段
        Field[] fields = entity.getClass().getDeclaredFields();
        Map<String, Boolean> fieldMap = new HashMap<>();
        for (Field field : fields) {
            fieldMap.put(field.getName(), true);
        }

        // 检查 JSON 中的键是否在实体类的字段中
        Iterator<String> fieldNames = jsonNode.fieldNames();
        while (fieldNames.hasNext()) {
            String jsonField = fieldNames.next();

            // 如果实体类没有 JSON 键
            if (!fieldMap.containsKey(jsonField)) {
                differences.put(jsonField, "Present in JSON, absent in Entity");
            } else {
                fieldMap.put(jsonField, false);
            }
        }

        // 检查实体类中未在 JSON 对应的字段
        for (Map.Entry<String, Boolean> entry : fieldMap.entrySet()) {
            if (entry.getValue()) {
                differences.put(entry.getKey(), "Present in Entity, absent in JSON");
            }
        }

        return differences;
    }

}

